<template>
    <div class="dept-stats">
      <div class="header">
        <h2>部门统计</h2>
        <el-button type="primary" @click="refreshStats" :icon="Refresh">
          刷新数据
        </el-button>
      </div>
  
      <!-- 统计图表区域 -->
      <div class="charts-container">
        <el-row :gutter="20">
          <!-- 部门人数统计柱状图 -->
          <el-col :span="16">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <span>部门人数统计</span>
                  <el-button type="primary" text @click="loadDeptStats">刷新</el-button>
                </div>
              </template>
              <div v-loading="loading.dept" class="chart-content">
                <div v-if="deptStats.length === 0" class="empty-data">暂无数据</div>
                <div v-else ref="deptChartRef" style="height: 500px;"></div>
              </div>
            </el-card>
          </el-col>
  
          <!-- 部门性别分布饼状图 -->
          <el-col :span="8">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <span>部门性别分布</span>
                  <el-tag v-if="selectedDept" type="primary">{{ selectedDept.deptName }}</el-tag>
                  <span v-else class="hint-text">点击左侧部门查看详情</span>
                </div>
              </template>
              <div v-loading="loading.gender" class="chart-content">
                <div v-if="!selectedDept" class="empty-data">
                  <el-icon><InfoFilled /></el-icon>
                  <p>请点击左侧柱状图选择部门</p>
                </div>
                <div v-else-if="genderStats.length === 0" class="empty-data">暂无性别分布数据</div>
                <div v-else ref="genderChartRef" style="height: 400px;"></div>
                
                <!-- 性别统计详情 -->
                <div v-if="selectedDept && genderStats.length > 0" class="gender-details">
                  <el-divider content-position="left">统计详情</el-divider>
                  <div class="stats-info">
                    <div class="info-item">
                      <span class="label">部门总人数:</span>
                      <span class="value">{{ selectedDept.employeeCount }} 人</span>
                    </div>
                    <div class="info-item" v-for="item in genderStats" :key="item.gender">
                      <span class="label">{{ getGenderLabel(item.gender) }}:</span>
                      <span class="value">{{ item.count }} 人 ({{ getPercentage(item.count, selectedDept.employeeCount) }})</span>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
  
      <!-- 部门统计表格 -->
      <el-card class="table-card" style="margin-top: 20px;">
        <template #header>
          <div class="chart-header">
            <span>部门统计详情</span>
            <el-button type="primary" text @click="loadDeptStats">刷新</el-button>
          </div>
        </template>
        <div class="table-content">
          <el-table 
            :data="deptStats" 
            border 
            stripe 
            highlight-current-row
            @row-click="handleRowClick"
            style="width: 100%"
          >
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="deptName" label="部门名称" min-width="150" />
            <el-table-column prop="employeeCount" label="员工人数" width="120" align="center">
              <template #default="{ row }">
                <el-tag :type="getCountTagType(row.employeeCount)">
                  {{ row.employeeCount }} 人
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="maleCount" label="男性" width="100" align="center">
              <template #default="{ row }">
                {{ row.maleCount || 0 }} 人
              </template>
            </el-table-column>
            <el-table-column prop="femaleCount" label="女性" width="100" align="center">
              <template #default="{ row }">
                {{ row.femaleCount || 0 }} 人
              </template>
            </el-table-column>
            <el-table-column label="性别比例" min-width="150" align="center">
              <template #default="{ row }">
                <el-progress 
                  :percentage="getMalePercentage(row)" 
                  :show-text="false"
                  style="margin-bottom: 5px;"
                />
                <div style="font-size: 12px; color: #909399;">
                  男 {{ getMalePercentage(row) }}% / 女 {{ getFemalePercentage(row) }}%
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleViewDetail(row)">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="deptStats.length === 0" class="empty-data">暂无数据</div>
        </div>
      </el-card>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, nextTick } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Refresh, InfoFilled } from '@element-plus/icons-vue'
  import { deptStatsApi } from '@/api/deptStats'
  import * as echarts from 'echarts'
  
  // 响应式数据
  const deptStats = ref([])
  const genderStats = ref([])
  const selectedDept = ref(null)
  
  // 加载状态
  const loading = reactive({
    dept: false,
    gender: false
  })
  
  // 图表引用
  const deptChartRef = ref()
  const genderChartRef = ref()
  
  // 图表实例
  let deptChart = null
  let genderChart = null
  
  // 生命周期
  onMounted(() => {
    loadDeptStats()
  })
  
  // 加载部门统计
  const loadDeptStats = async () => {
    try {
      loading.dept = true
      const response = await deptStatsApi.getDeptEmployeeStats()
      if (response && response.code === 1) {
        deptStats.value = response.data || []
        nextTick(() => {
          renderDeptChart()
        })
      } else {
        ElMessage.error(response?.msg || '获取部门统计失败')
      }
    } catch (error) {
      ElMessage.error('获取部门统计失败')
      console.error('Error loading dept stats:', error)
    } finally {
      loading.dept = false
    }
  }
  
  // 加载部门性别分布
  const loadGenderStats = async (deptId) => {
    try {
      loading.gender = true
      const response = await deptStatsApi.getDeptGenderStats(deptId)
      if (response && response.code === 1) {
        genderStats.value = response.data || []
        nextTick(() => {
          renderGenderChart()
        })
      } else {
        ElMessage.error(response?.msg || '获取性别分布失败')
      }
    } catch (error) {
      ElMessage.error('获取性别分布失败')
      console.error('Error loading gender stats:', error)
    } finally {
      loading.gender = false
    }
  }
  
  // 渲染部门统计柱状图
  const renderDeptChart = () => {
    if (!deptChartRef.value || deptStats.value.length === 0) return
    
    if (deptChart) {
      deptChart.dispose()
    }
    
    deptChart = echarts.init(deptChartRef.value)
    
    // 美观的颜色方案
    const colorPalette = [
      '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de',
      '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc', '#1e90ff',
      '#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57'
    ]
    
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: function(params) {
          const data = params[0]
          const deptData = deptStats.value[params[0].dataIndex]
          return `
            <div style="font-weight: bold; margin-bottom: 5px; color: #333;">${data.name}</div>
            <div style="display: flex; align-items: center; margin: 5px 0;">
              <span style="display: inline-block; width: 8px; height: 8px; background: ${colorPalette[params[0].dataIndex % colorPalette.length]}; margin-right: 5px; border-radius: 2px;"></span>
              <span>员工人数: </span>
              <span style="color: #5470c6; font-weight: bold; margin-left: 5px;">${data.value} 人</span>
            </div>
            <div style="color: #666; font-size: 12px;">
              男性: ${deptData.maleCount || 0}人 | 女性: ${deptData.femaleCount || 0}人
            </div>
          `
        }
      },
      legend: {
        show: false
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: deptStats.value.map(item => item.deptName),
        axisLabel: {
          rotate: 45,
          interval: 0,
          color: '#666',
          fontSize: 12
        },
        axisLine: {
          lineStyle: {
            color: '#ddd'
          }
        },
        axisTick: {
          alignWithLabel: true
        }
      },
      yAxis: {
        type: 'value',
        name: '员工人数',
        nameTextStyle: {
          color: '#666',
          padding: [0, 0, 0, -30]
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#ddd'
          }
        },
        axisLabel: {
          color: '#666'
        },
        splitLine: {
          lineStyle: {
            color: '#f0f0f0',
            type: 'dashed'
          }
        }
      },
      series: [
        {
          name: '员工人数',
          type: 'bar',
          data: deptStats.value.map((item, index) => ({
            value: item.employeeCount,
            itemStyle: {
              color: colorPalette[index % colorPalette.length],
              borderRadius: [4, 4, 0, 0],
              borderWidth: 0
            }
          })),
          barWidth: '60%',
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.3)'
            }
          },
          label: {
            show: true,
            position: 'top',
            color: '#333',
            fontWeight: 'bold',
            formatter: '{c}人'
          }
        }
      ]
    }
    
    deptChart.setOption(option)
    
    // 添加点击事件
    deptChart.off('click')
    deptChart.on('click', (params) => {
      const deptIndex = params.dataIndex
      const dept = deptStats.value[deptIndex]
      handleDeptSelect(dept)
    })
  }
  
  // 渲染性别分布饼状图
  const renderGenderChart = () => {
    if (!genderChartRef.value || genderStats.value.length === 0) return
    
    if (genderChart) {
      genderChart.dispose()
    }
    
    genderChart = echarts.init(genderChartRef.value)
    
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}人 ({d}%)',
        backgroundColor: 'rgba(255, 255, 255, 0.9)',
        borderColor: '#ddd',
        borderWidth: 1,
        textStyle: {
          color: '#333'
        }
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        top: 'top',
        itemGap: 10,
        textStyle: {
          color: '#666',
          fontSize: 12
        },
        formatter: function(name) {
          const data = genderStats.value.find(item => getGenderLabel(item.gender) === name)
          return `${name}: ${data ? data.count : 0}人`
        }
      },
      series: [
        {
          name: '性别分布',
          type: 'pie',
          radius: ['50%', '70%'],
          center: ['50%', '55%'],
          avoidLabelOverlap: true,
          itemStyle: {
            borderRadius: 8,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            formatter: '{d}%',
            color: '#333',
            fontWeight: 'bold'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 14,
              fontWeight: 'bold'
            },
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.3)'
            }
          },
          labelLine: {
            show: true,
            length: 10,
            length2: 10
          },
          data: genderStats.value.map(item => ({
            value: item.count,
            name: getGenderLabel(item.gender),
            itemStyle: {
              color: item.gender === 1 ? '#5470c6' : '#ee6666'
            }
          }))
        }
      ]
    }
    
    genderChart.setOption(option)
  }
  
  // 处理部门选择
  const handleDeptSelect = (dept) => {
    selectedDept.value = dept
    loadGenderStats(dept.deptId)
    
    // 高亮表格行
    const tableRows = document.querySelectorAll('.el-table__row')
    tableRows.forEach(row => row.classList.remove('current-row'))
    const targetRow = Array.from(tableRows).find(row => 
      row.querySelector('.el-table__cell').textContent === (deptStats.value.findIndex(d => d.deptId === dept.deptId) + 1).toString()
    )
    if (targetRow) {
      targetRow.classList.add('current-row')
    }
  }
  
  // 表格行点击事件
  const handleRowClick = (row) => {
    handleDeptSelect(row)
  }
  
  // 查看详情
  const handleViewDetail = (row) => {
    handleDeptSelect(row)
  }
  
  // 刷新所有统计
  const refreshStats = () => {
    loadDeptStats()
    selectedDept.value = null
    genderStats.value = []
  }
  
  // 工具方法
  const getGenderLabel = (gender) => {
    const genderMap = {
      0: '女性',
      1: '男性'
    }
    return genderMap[gender] || '未知'
  }
  
  const getPercentage = (count, total) => {
    if (!total) return '0%'
    return ((count / total) * 100).toFixed(1) + '%'
  }
  
  const getMalePercentage = (row) => {
    const total = row.employeeCount
    const maleCount = row.maleCount || 0
    if (!total) return 0
    return Math.round((maleCount / total) * 100)
  }
  
  const getFemalePercentage = (row) => {
    const total = row.employeeCount
    const femaleCount = row.femaleCount || 0
    if (!total) return 0
    return Math.round((femaleCount / total) * 100)
  }
  
  const getCountTagType = (count) => {
    if (count >= 50) return 'danger'
    if (count >= 20) return 'warning'
    if (count >= 10) return 'primary'
    return 'success'
  }
  
  // 组件卸载时销毁图表
  const destroyCharts = () => {
    if (deptChart) {
      deptChart.dispose()
      deptChart = null
    }
    if (genderChart) {
      genderChart.dispose()
      genderChart = null
    }
  }
  </script>
  
  <style scoped>
  .dept-stats {
    padding: 20px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
  }
  
  .charts-container {
    margin-bottom: 20px;
  }
  
  .chart-card {
    border-radius: 8px;
    border: none;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .hint-text {
    font-size: 12px;
    color: #909399;
  }
  
  .chart-content {
    padding: 10px 0;
  }
  
  .empty-data {
    text-align: center;
    color: #909399;
    padding: 50px 0;
    font-size: 14px;
  }
  
  .empty-data .el-icon {
    font-size: 48px;
    margin-bottom: 10px;
    color: #c0c4cc;
  }
  
  .gender-details {
    margin-top: 20px;
  }
  
  .stats-info {
    padding: 0 10px;
  }
  
  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .info-item:last-child {
    border-bottom: none;
  }
  
  .info-item .label {
    color: #606266;
    font-size: 14px;
  }
  
  .info-item .value {
    color: #303133;
    font-weight: 500;
  }
  
  .table-card {
    border-radius: 8px;
    border: none;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  .table-content {
    padding: 10px 0;
  }
  
  :deep(.el-card__header) {
    padding: 15px 20px;
    border-bottom: 1px solid #ebeef5;
  }
  
  :deep(.el-table .current-row) {
    background-color: #f0f9ff !important;
  }
  
  :deep(.el-table .el-table__row:hover) {
    cursor: pointer;
  }
  
  :deep(.el-table .el-table__row:hover td) {
    background-color: #f5f7fa !important;
  }
  </style>